package com.shi.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.shi.common.Result;
import com.shi.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

import static com.shi.constants.RedisConstant.CHECK_CODE_TTL;
import static com.shi.constants.SysConstant.*;

@Api(tags = "图片验证码功能")
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @ApiOperation("生成图片验证码")
    @GetMapping("/generate")
    public Result generate(@ApiParam(hidden = true) HttpServletResponse response) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(CAPTCHA_WIDTH, CAPTCHA_HEIGHT);
        MathGenerator mathGenerator = new MathGenerator(Math_Generator_NUM_LENGTH);
        lineCaptcha.setGenerator(mathGenerator);
        lineCaptcha.createCode();
        String checkCodeKey= UUID.randomUUID().toString();
        RedisUtil.set(checkCodeKey,lineCaptcha.getCode(), CHECK_CODE_TTL);
        String imageBase64 = lineCaptcha.getImageBase64();
        return Result.ok(Map.of("checkCodeKey",checkCodeKey,"imageBase64",imageBase64));
    }
}
